package com.example.netty.io.server

import com.example.netty.io.core.AbsConnector
import com.example.netty.io.core.EventType
import com.example.netty.io.core.IMessageListener
import com.example.netty.io.core.NettyConfigure
import com.example.netty.moshi.tMoshi
import com.example.netty.pojo.TestPojo
import io.netty.channel.Channel
import io.netty.channel.ChannelHandlerContext

/**
 * File Name :NettyServer
 * Author : luqihua
 * Date : 2024/4/15
 * Desc :
 **/

class NettyServer(private val port: Int) : IMessageListener, AbsConnector() {

    private val task = NettyServerTask(port, this)
    private val clientMap = HashMap<String, ChannelHandlerContext>()
    override fun start() {
        NettyConfigure.executor.execute(task)
    }

    override fun stop() {
        clientMap.onEach {
            try {
                it.value.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }.clear()
        task.close()
    }

    override fun onMessageArrived(channel: Channel, message: String) {
        val testPojo = TestPojo(100, "this is a json string")
        val adapter = tMoshi.adapter<TestPojo>(TestPojo::class.java)
        val json = adapter.toJson(testPojo)
        channel.writeAndFlush(json)
    }

    override fun onEventArrived(channel: Channel, type: EventType) {

    }

    override fun getHeartbeat(): ByteArray {
//        return "Heartbeat from Server".toByteArray()
        return ByteArray(0)
    }
}